package cn.cuilan.other.hsbpy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.SqlBuilder;
import cn.hutool.db.sql.Wrapper;
import cn.hutool.http.HttpRequest;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 含漱爆破液店铺导入测试
 *
 * @author Joey
 * @date 2020-10-26
 */
public class HsbpyShopImport {

    public static void main(String[] args) throws InterruptedException {
        //test
//        importShopData(ConfigInfo.buildTestConfig(), "/Users/zhangyan/Downloads/importShop.xlsx");

        //online
//        importShopData(ConfigInfo.buildOnlineConfig(), "/Users/zhangyan/Downloads/importShop.xlsx");
    }

    public static void importShopData(ConfigInfo configInfo, String... excelFiles) throws InterruptedException {
        String loginToken = getLoginToken(configInfo);

        if (StrUtil.isBlank(loginToken)) {
            System.out.println("登陆失效:" + configInfo);
            return;
        }

        System.out.println("loginToken:" + loginToken);

        List<ShopInfo> importShopInfoList = new ArrayList<>();

        //读取店铺信息
        for (String excelFile : excelFiles) {
            ExcelReader reader = ExcelUtil.getReader(ResourceUtil.getStream(excelFile));
            List<ShopInfo> shopInfoList = reader.readAll(ShopInfo.class);

            importShopInfoList.addAll(shopInfoList);
        }

        System.out.println("importShopListSize:" + importShopInfoList.size());

        //打印查询sql
        printSql(importShopInfoList);

        //导入店铺信息
        for (int i = 0; i < importShopInfoList.size(); i++) {
            System.out.println("importShopIndex=" + i);
            importData(configInfo, loginToken, importShopInfoList.get(i));
        }
    }

    private static void printSql(List<ShopInfo> importShopInfoList) {
        String sql = SqlBuilder.create(new Wrapper())
                                .select()
                                .from("t_shop")
                                .where("1=1 AND ")
                                .in("posShopId", importShopInfoList.stream().map(s -> s.getPosShopId()).collect(Collectors.toList()))
                                .build();
        System.out.println(sql);
    }

    private static void importData(ConfigInfo configInfo, String loginToken, ShopInfo shopInfo) throws InterruptedException {
        long st = System.currentTimeMillis();
        System.out.println("Import shop start.shopInfo=" + shopInfo);

        String importResp = HttpRequest.post(configInfo.getImportDataUrl())
                                       .header("userToken", loginToken)
                                       .body(JSON.toJSONString(shopInfo))
                                       .execute()
                                       .body();

        //导入店铺后端是异步执行 所以需要睡眠等待结果
        TimeUnit.SECONDS.sleep(3);

        String resultResp = HttpRequest.get(configInfo.getQueryImportResultResult())
                                       .header("userToken", loginToken)
                                       .form(BeanUtil.beanToMap(shopInfo))
                                       .execute()
                                       .body();
        System.out.println("Import shop result.shopInfo=" + shopInfo + ",result=" + resultResp);

        System.out.println("Import shop end.posGroupId=" + shopInfo + ",timeCost=" + (System.currentTimeMillis() - st) + "ms");
    }

    /**
     * 获取登陆token
     *
     * @param configInfo
     * @return
     */
    private static String getLoginToken(ConfigInfo configInfo) {
        JSONObject loginRequest = new JSONObject();
        loginRequest.put("phone", configInfo.getUsername());
        loginRequest.put("password", configInfo.getPass());

        String loginResp = HttpRequest.post(configInfo.getLoginUrl())
                                      .body(JSON.toJSONString(loginRequest))
                                      .execute()
                                      .body();
        System.out.println(loginResp);

        return JSONPath.read(loginResp, "$.data.userToken").toString();
    }

    @Getter
    @Setter
    public static class ShopInfo {
        private String posGroupId;

        private String posShopId;

        private String shopName;

        @Override
        public String toString() {
            return JSONObject.toJSONString(this);
        }
    }

    @Data
    @Builder
    public static class ConfigInfo {
        private static final String TEST_BASE_URL = "https://test-admin-hsbpy.hualala.com";

        private static final String ONLINE_BASE_URL = "https://admin-hsbpy.hualala.com";

        private static final String LOGIN_URL_SUFFIX = "/api/user/login";

        private static final String IMPORT_POS_DATA_URL_SUFFIX = "/api/shop/importPosData";

        private static final String QUERY_IMPORT_RESULT_URL_SUFFIX = "/api/shop/queryImportResult";

        private String username;

        private String pass;

        private String loginUrl;

        private String importDataUrl;

        private String queryImportResultResult;

        public static ConfigInfo buildTestConfig() {
            return new ConfigInfoBuilder().username("16666666666")
                                          .pass("123456")
                                          .loginUrl(TEST_BASE_URL + LOGIN_URL_SUFFIX)
                                          .importDataUrl(TEST_BASE_URL + IMPORT_POS_DATA_URL_SUFFIX)
                                          .queryImportResultResult(TEST_BASE_URL + QUERY_IMPORT_RESULT_URL_SUFFIX)
                                          .build();
        }

        public static ConfigInfo buildOnlineConfig() {
            return new ConfigInfoBuilder().username("16666666668")
                                          .pass("123456")
                                          .loginUrl(ONLINE_BASE_URL + LOGIN_URL_SUFFIX)
                                          .importDataUrl(ONLINE_BASE_URL + IMPORT_POS_DATA_URL_SUFFIX)
                                          .queryImportResultResult(ONLINE_BASE_URL + QUERY_IMPORT_RESULT_URL_SUFFIX)
                                          .build();
        }
    }
}
